package com.lsp.helper;

import com.lsp.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BeanHelper {

    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();

    static {
        //获取应用中所有的bean
        Set<Class<?>> beanClassSet = ClassHelper.getClassSet();
        //将bean实例化,放到bean容器中
         for (Class<?> beanClass : beanClassSet){
             Class<?> superclass = beanClass.getSuperclass() ;
             if(Object.class.equals(superclass)){
                 Object obj = ReflectionUtil.newInstance(beanClass);
                 BEAN_MAP.put(beanClass,obj);
             }
         }
    }

    public static Map<Class<?>, Object> getBeanMap(){
        return BEAN_MAP;
    }

    public static <T> T getBean(Class<T> cls){
        if(!BEAN_MAP.containsKey(cls)){
            throw new RuntimeException("can not get bean by class: " + cls);
        }
        return (T) BEAN_MAP.get(cls);
    }

    /**
     * 设置Bean实例
     * @param clss
     * @param object
     */
    public static void setBean(Class<?> clss, Object object) {
        BEAN_MAP.put(clss,object);
    }
}
